package com.example.pei.ithinklearnt.present;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.Toast;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.view.interfaces.PersonalInterface;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

import static com.example.pei.ithinklearnt.utils.PermisionUtil.checkWritePermission;
import static com.example.pei.ithinklearnt.utils.PhotoUtil.cropImageUri;
import static com.example.pei.ithinklearnt.utils.PhotoUtil.getPathFromAlbum;
import static com.example.pei.ithinklearnt.utils.PhotoUtil.updateUriFromFile;
import static com.example.pei.ithinklearnt.utils.PhotoUtil.updateUriFromPath;


/**
 * Created by Pei on 2017/12/6.
 */

public class PersonalPresentImp implements PersonalPresent {

    private PersonalInterface personalInterface;
    private UserInfo currentUser;
    private UserInfo displayUser;

    private File coverOutputCropImage;   //封面裁剪后的文件，即上传到服务器中的文件
    private Uri coverimageCropUri;             //上面这个文件的URL
    private String coverPath;         //选择的封面在本地的存储路径,如果是相机拍的图片，则为拍摄图片的存储路径，如果是相册选择的图片，则为选择的图片的路径
    // ，但最终裁剪后的路径不是这里，和下面的服务器下载到本地的位置相同
    private String localCoverPath; //封面从服务器下载到本地的位置


    private File headOutputCropImage;   //头像裁剪后的文件，即上传到服务器中的文件
    private Uri headimageCropUri;             //上面这个文件的URL
    private String headPath;//选择的头像在本地的存储路径，但最终裁剪后的路径不是这里，和下面的服务器下载到本地的位置相同
    private String localheadPath;//头像从服务器下载到本地的位置


    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int CROP_REQUEST_CODE = 3;

    private final int ALL = 104;
    private final int onlyWrite=103;

    public PersonalPresentImp(PersonalInterface personalInterface,UserInfo displayUser){
        this.personalInterface=personalInterface;
        currentUser= AppApplication.getCurrentUser();
        this.displayUser=displayUser;
    }


    @Override
    public void getCoverImage() {
        String coverPath;
        coverPath=personalInterface.getActivityy().getExternalCacheDir()+"/cover-"+displayUser.getUsername()+".jpg";
        File coverfile=new File(coverPath);
        if(!coverfile.exists()){
            //如果本地不存在文件 则加载网络图片
            personalInterface.setCoverImageBitmap(displayUser.getCoverFileUrl());
        }else {
            //本地存在封面文件，直接使用
            Bitmap bitmap = BitmapFactory.decodeFile(coverPath);
            personalInterface.setCoverImageBitmap(bitmap);
        }
    }

    @Override
    public void getHeadImage() {
        String headPath=personalInterface.getActivityy().getExternalCacheDir()+"/head-"+displayUser.getUsername()+".jpg";
        File headfile=new File(headPath);
        if(!headfile.exists()){
            personalInterface.setHeadImageBitmap(displayUser.getHeadFileUrl());
            //如果本地不存在头像 则进行下载
//            downloadHeadFile(new downloadHeadListener() {
//                @Override
//                public void downloadHeadDone(String path) {
//                    Bitmap bitmap = BitmapFactory.decodeFile(path);
//                    personalInterface.setHeadImageBitmap(bitmap);
//                }
//            });
        }else {
            //本地存在头像文件，直接使用
            Bitmap bitmap = BitmapFactory.decodeFile(headPath);
            personalInterface.setHeadImageBitmap(bitmap);
        }
    }


//    public interface downloadCoverListener {
//        void downloadCoverDone(String path);
//    }
//    public void downloadCoverFile(downloadCoverListener listener) {
//        final downloadCoverListener coverDownloadListener = listener;
//        //如果服务器里面没有 为空怎么办
//        if (currentUser.getCoverFileUrl() == null) {
//            return;
//        }
//        BmobFile file = new BmobFile("CoverImage" + currentUser.getMobilePhoneNumber() + ".jpg", "", currentUser.getCoverFileUrl());
//        //允许设置下载文件的存储路径，默认下载文件的目录为：context.getApplicationContext().getCacheDir()+"/bmob/"
//        File saveFile = new File(personalInterface.getActivityy().getExternalCacheDir(), file.getFilename());
//        file.download(saveFile, new DownloadFileListener() {
//            @Override public void onStart() {}
//            @Override public void onProgress(Integer value, long newworkSpeed) {}
//            @Override
//            public void done(String savePath, BmobException e) {
//                if (e == null) {
//                    //savePath为下载到本地的路径
//                    //localCoverPath = savePath;
//                    coverDownloadListener.downloadCoverDone(savePath);
//                }
//            }
//        });
//    }
//
//
//    public interface downloadHeadListener {
//        void downloadHeadDone(String path);
//    }
//    public void downloadHeadFile(downloadHeadListener listener) {
//        final downloadHeadListener headDownloadListener = listener;
//        //headFileUrl 为空怎么办
//        if (currentUser.getHeadFileUrl() == null) {
//            return;
//        }
//        BmobFile file = new BmobFile("HeadImage" + currentUser.getMobilePhoneNumber() + ".jpg", "", currentUser.getHeadFileUrl());
//        //允许设置下载文件的存储路径，默认下载文件的目录为：context.getApplicationContext().getCacheDir()+"/bmob/"
//        File saveFile = new File(personalInterface.getActivityy().getExternalCacheDir(), file.getFilename());
//        file.download(saveFile, new DownloadFileListener() {
//            @Override public void onStart() {}
//            @Override public void onProgress(Integer value, long newworkSpeed) {}
//            @Override
//            public void done(String savePath, BmobException e) {
//                if (e == null) {
//                    //   Toast.makeText(MainActivity.this, "下载成功 保存路径:"+savePath, Toast.LENGTH_SHORT).show();
//                    headDownloadListener.downloadHeadDone(savePath);
//                }
//            }
//        });
//    }

    //aim==1，则是为头像，2是为封面
    @Override
    public void getPhotoAndCrop(int aim,Uri uri,int style,int requestCode,int x,int y) {
        Context context=personalInterface.getActivityy();
        if(aim==1){
            headOutputCropImage=new File(context.getExternalCacheDir(), "head-" + currentUser.getUsername() + ".jpg");
        }else if(aim==2){
            coverOutputCropImage=new File(context.getExternalCacheDir(), "cover-" + currentUser.getUsername() + ".jpg");
        }

        if(style==IMAGE_REQUEST_CODE){
            //如果是先从相册中选择的照片的路径
            if(aim==1) {
                headPath = getPathFromAlbum(context, uri);
            }else if(aim==2){
                coverPath = getPathFromAlbum(context, uri);
            }
        }else if(style==CAMERA_REQUEST_CODE){
            //如果是从相机拍照选择的
            //因为在启动相机的时候已经设置好了headPath的值，所以这里不需要再次设置
        }
        if(aim==1) {
            headimageCropUri = cropImageUri(personalInterface.getActivityy(),personalInterface.get(),
                    updateUriFromPath(context, headPath), headOutputCropImage,
                    1, 1, 500, 500, CROP_REQUEST_CODE);
        }else if(aim==2){
            coverimageCropUri = cropImageUri(personalInterface.getActivityy(),personalInterface.get(),
                    updateUriFromPath(context, coverPath), coverOutputCropImage,
                    x, y, x, y, CROP_REQUEST_CODE);
        }
    }

    @Override
    public void choosePhotoFromAlbum(int requestCode) {
        //检查读写权限
        if(checkWritePermission(personalInterface.getActivityy(),onlyWrite)){
            openAlbum(IMAGE_REQUEST_CODE);   //拥有读写权限
        }
    }
    @Override
    public void openAlbum(int requestCode) {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        personalInterface.get().startActivityForResult(intent, requestCode);
    }

    @Override
    public void choosePhotoFromCamera(int requestCode) {
        //相机拍摄的临时文件
        File outputImage=new File(personalInterface.getActivityy().getExternalCacheDir(),"tmpCameraImage"+currentUser.getMobilePhoneNumber()+".jpg");
        try {
            if(outputImage.exists()){
                outputImage.delete();
            }
            outputImage.createNewFile();
            headPath=outputImage.getPath();
            coverPath=outputImage.getPath();
        }catch (IOException e){
            e.printStackTrace();
        }

        Uri imageUri=updateUriFromFile(personalInterface.getActivityy(),outputImage);
        // 启动相机
        Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        personalInterface.get().startActivityForResult(intent,requestCode);
    }

    @Override
    public void CropCallback(int aim,Intent data) {
        //显示裁剪后的图片
        if(aim==1) {            //头像
            if (headimageCropUri != null) {
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(personalInterface.getActivityy().getContentResolver().openInputStream(headimageCropUri));
                    personalInterface.setHeadImageBitmap(bitmap);        //设置view 中的头像

                    //服务器中已经有头像，则应该删除
                    if (currentUser.getHeadFileUrl() != null) {
                        BmobFile file = new BmobFile();
                        file.setUrl(currentUser.getHeadFileUrl());//此url是上传文件成功之后通过bmobFile.getUrl()方法获取的。
                        file.delete(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                    //删除成功，则上传新封面到服务器中
                                    upLoadHead();
                                } else {
                                    if (e.getErrorCode() == 151) {
                                        //uri错误,服务器没有此图片
                                        upLoadHead();
                                    }
                                }
                            }
                        });
                    } else {
                        //服务器没有封面，直接上传
                        upLoadHead();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }else if(aim==2){       //封面
            if (coverimageCropUri != null) {
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(personalInterface.getActivityy().getContentResolver().openInputStream(coverimageCropUri));
                    personalInterface.setCoverImageBitmap(bitmap);

                    //服务器中已经有封面，则应该删除
                    if (currentUser.getCoverFileUrl() != null) {
                        BmobFile file = new BmobFile();
                        file.setUrl(currentUser.getCoverFileUrl());//此url是上传文件成功之后通过bmobFile.getUrl()方法获取的。
                        file.delete(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                    //删除成功，则上传新封面到服务器中
                                    upLoadCover();
                                } else {
                                    if (e.getErrorCode() == 151||e.getErrorCode()==9018) {
                                        //uri错误,服务器没有此图片
                                        upLoadCover();
                                    }
                                }
                            }
                        });
                    } else {
                        //服务器没有封面，直接上传
                        upLoadCover();
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }
    }
    private void upLoadCover() {
        final BmobFile coverBmobFile = new BmobFile(coverOutputCropImage);
        coverBmobFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    UserInfo newInfo=new UserInfo();
                    newInfo.setCoverFileUrl(coverBmobFile.getFileUrl());
                    newInfo.update(currentUser.getObjectId(), new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                personalInterface.setShowSnackbar(true,1);    //设置成功
                            } else {
                                personalInterface.setShowSnackbar(false,1);   //设置失败
                            }
                        }
                    });
                } else {
                    Toast.makeText(personalInterface.getActivityy(), "封面上传失败" + e.getErrorCode() + "   " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void upLoadHead() {
        final BmobFile headBmobFile = new BmobFile(headOutputCropImage);
        headBmobFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    UserInfo newInfo=new UserInfo();
                    newInfo.setHeadFileUrl(headBmobFile.getFileUrl());
                    currentUser.setHeadFileUrl(headBmobFile.getFileUrl());
                    newInfo.update(currentUser.getObjectId(), new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                personalInterface.setShowSnackbar(true,0);    //设置成功
                                //发送更新事件
                               // EventBus.getDefault().post(new RefreshEvent());
                                AppApplication.setCurrentUser(currentUser);

                                //会话：2.7、更新用户资料，用于在会话页面、聊天页面以及个人信息页面显示
                                BmobIM.getInstance().
                                        updateUserInfo(new BmobIMUserInfo(currentUser.getObjectId(),
                                                currentUser.getNickName(), currentUser.getHeadFileUrl()));

                            } else {
                                personalInterface.setShowSnackbar(false,0);   //设置失败
                            }
                        }
                    });
                } else {
                    Toast.makeText(personalInterface.getActivityy(), "头像上传失败" + e.getErrorCode() + "   " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
